package com.model;

import java.io.IOException;
import java.util.Calendar;

import com.imax.vmall.sdk.android.common.adapter.ServiceCallback;
import com.imax.vmall.sdk.android.entry.CapabilityService;
import com.imax.vmall.sdk.android.entry.CommonService;
import com.imax.vmall.sdk.android.huawei.city.CityService;
import com.imax.vmall.sdk.android.huawei.weather.WeatherService;
import com.model.location.City;
import com.model.location.Province;
import com.model.wallpaper.WallPaper;
import com.model.weather.Weather;
import com.receiver.DayReceiver;
import com.receiver.NightReceiver;
import com.receiver.UpdateReceiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

/**
 * 该类保存基本的用户设置
 * 单例模式
 * @author Sgarlic
 *
 */
public class User {
	private static User instance = null;
	
	
	// user attributes
	private MyTime dayStartTime;// 白天的起始时间
	private MyTime dayEndTime;// 白天的结束时间
	private int autoUpdateInterval;//小时的整数倍，更新天气的时间间隔
	private boolean screenSaver;// 是否同步为屏保
	private City city;// 用户选择的城市
	private Province province; // 用户选择的省份
	private boolean firstInit;//判断用户是否第一次使用程序
	private Context context;
	private Weather currentWeather;
	
	//By GY 三个Alarm
	private AlarmManager dayAM;
	private Intent dayIntent;
	private PendingIntent daySender;
	
	private AlarmManager nightAM;
	private Intent nightIntent;
	private PendingIntent nightSender;
	
	private AlarmManager updateAM;
	private Intent updateIntent;
	private PendingIntent updateSender;
	
	// 定义SharedPreferences文件中的键
	private final String DayStartTime = "DayStartTime";//xx:xx表示xx点xx分
	private final String DayEndTime = "DayEndTime";
	private final String AutoUpdateInterval = "AutoUpdateInterval";
	private final String ScreenSaver = "ScreenSaver";
	private final String City = "City";
	private final String Province = "Province";
	private final String FirstInit = "FirstInit";
	
	//华为服务的类
	private CommonService commonService;
    private WeatherService weather;
    
    private Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what)
            {
                case 1://获取天气成功
                	resetWallpaperNow();
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
            }
        }
    };
    
	private User(Context context){
		this.context = context;
		
		//By GY
		dayAM=(AlarmManager)context.getSystemService(context.ALARM_SERVICE);
		dayIntent=new Intent(context,DayReceiver.class);
		daySender=PendingIntent.getBroadcast(context, 0, dayIntent, 0);
		
		nightAM=(AlarmManager)context.getSystemService(context.ALARM_SERVICE);
		nightIntent=new Intent(context,NightReceiver.class);
		nightSender=PendingIntent.getBroadcast(context, 0, nightIntent, 0);
		
		updateAM=(AlarmManager)context.getSystemService(context.ALARM_SERVICE);
		updateIntent=new Intent(context,UpdateReceiver.class);
		updateSender=PendingIntent.getBroadcast(context, 0, updateIntent, 0);

		//初始化华为服务
		//实例化CommonService
        commonService=CommonService.getInstance();
        //应用ID，请去iMAX平台注册申请
        String appId="3029095016";
        //应用Key
        String appKey="1ab7f515d630555e3790636ecf2d8923";
        //通过CommonService调用鉴权接口，在调用其它能力前必须保证鉴权初始化成功
        commonService.init(this.context,appId, appKey, new ServiceCallback() {
            public void onError(String arg0) {
        		Toast.makeText(User.this.context, "SDK初始化鉴权失败", Toast.LENGTH_SHORT).show();
            }
            
            public void onComplete(String arg0) {
            	//Toast.makeText(User.this.context, "SDK初始化鉴权成功", Toast.LENGTH_SHORT).show();
            }
        });
        weather = CapabilityService.getWeatherServiceInstance();
		
		getUserData();//获得用户数据
	}
	
	public static User getUser(Context context){
		if(instance==null)
			instance = new User(context);
		return instance;
	}
	
	/**
	 * 保存用户的设置
	 * @param userPreferences
	 */
	public void saveUserData(){
		SharedPreferences userPreferences = context.getSharedPreferences("WeatherWP",Context.MODE_PRIVATE);
		//开始修改SharedPreferences的数据，默认设置
		SharedPreferences.Editor editor = userPreferences.edit();
		editor.putString(DayStartTime,this.dayStartTime.toString());
		editor.putString(DayEndTime,this.dayEndTime.toString());
		editor.putInt(AutoUpdateInterval, this.autoUpdateInterval);
		
		//By GY
		saveChangingTime(dayStartTime,dayEndTime);
		saveUpdateInterval(autoUpdateInterval);
		//在这里更新一次就好了。。
		getCurrentWeather();
		
		editor.putBoolean(ScreenSaver, this.screenSaver);
		editor.putString(Province, province.getProvinceName());
		editor.putString(City, city.getCityName());
		editor.putBoolean(FirstInit, false);
		editor.commit();
	}
	private void getUserData(){
		//获取用户的SharedPreferences文件
		// 第一个参数是存取时的名字
		SharedPreferences userPreferences = context.getSharedPreferences("WeatherWP",Context.MODE_PRIVATE);
		
		//读取用户设置， 如果没有该选项，就读取用户的默认设置，
		this.dayStartTime = new MyTime(userPreferences.getString(DayStartTime, "06:00"));
		this.dayEndTime = new MyTime(userPreferences.getString(DayEndTime, "18:00"));
		this.autoUpdateInterval = userPreferences.getInt(AutoUpdateInterval, 1);
		this.screenSaver = userPreferences.getBoolean(ScreenSaver, false);
		this.province = getProvinceFromName(userPreferences.getString(Province, "北京"));
		this.city = getCityFromName(userPreferences.getString(City, "无"));
		this.firstInit = userPreferences.getBoolean(FirstInit, true);
	}
	
	private Province getProvinceFromName(String provinceName){
		boolean municipalities = false;
		if(provinceName.equals("北京")||provinceName.equals("上海")||provinceName.equals("天津")
				||provinceName.equals("重庆")||provinceName.equals("香港")||provinceName.equals("澳门"))
			municipalities = true;
		Province tempProvince = new Province(101,CnToSpell.getPingYin(provinceName),provinceName,municipalities);
		return tempProvince;
	}
	
	private City getCityFromName(String cityName){
		Province parentProvince = null;
		if(!this.province.isMunicipalities())
			parentProvince = this.province;
		City tempCity= new City(101,CnToSpell.getPingYin(cityName),cityName,parentProvince);
		return tempCity;
	}

	
	public MyTime getDayStartTime() {
		return dayStartTime;
	}

	public void setDayStartTime(MyTime dayStartTime) {
		this.dayStartTime = dayStartTime;
	}

	public MyTime getDayEndTime() {
		return dayEndTime;
	}

	public void setDayEndTime(MyTime dayEndTime) {
		this.dayEndTime = dayEndTime;
	}

	public int getAutoUpdateInterval() {
		return autoUpdateInterval;
	}

	public void setAutoUpdateInterval(int autoUpdateInterval) {
		this.autoUpdateInterval = autoUpdateInterval;
	}

	public boolean isScreenSaver() {
		return screenSaver;
	}

	public void setScreenSaver(boolean screenSaver) {
		this.screenSaver = screenSaver;
	}

	public City getCity() {
		return city;
	}

	public void setCity(City city) {
		this.city = city;
	}

	public boolean isFirstInit() {
		return firstInit;
	}

	public void setFirstInit(boolean firstInit) {
		this.firstInit = firstInit;
	}
	
	//By GY
	/*
	 * 将dayStart作为一个AlarmManager的开始运行时间，将dayEnd作为另一个AlarmManager的开始运行时间
	 * 两个AlarmManager的重复运行间隔都是24小时
	 * Receiver事件为依据当前天气和时间（白天/夜晚）更换壁纸
	 */
	private void saveChangingTime(MyTime dayStart,MyTime dayEnd){
		Calendar calendar=Calendar.getInstance();
		long dayStartTimeMilli;
		long dayEndTimeMilli;
		MyTime currentTime=new MyTime(calendar.get(Calendar.MINUTE),calendar.get(Calendar.HOUR_OF_DAY));
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		//currentTime<dayStart
		if(MyTime.compareTime(currentTime,dayStart)==-1){
			calendar.set(Calendar.HOUR_OF_DAY, dayStart.getHour());
			calendar.set(Calendar.MINUTE, dayStart.getMinute());
			dayStartTimeMilli=calendar.getTimeInMillis();
			
			calendar.set(Calendar.HOUR_OF_DAY, dayEnd.getHour());
			calendar.set(Calendar.MINUTE, dayEnd.getMinute());
			dayEndTimeMilli=calendar.getTimeInMillis();
		}//dayStart<=currentTime<dayEnd
		else if((MyTime.compareTime(dayStart, currentTime)==-1||MyTime.compareTime(dayStart, currentTime)==0)&&MyTime.compareTime(currentTime, dayEnd)==-1){
			calendar.set(Calendar.HOUR_OF_DAY, dayEnd.getHour());
			calendar.set(Calendar.MINUTE, dayEnd.getMinute());
			dayEndTimeMilli=calendar.getTimeInMillis();
			
			calendar.add(Calendar.DATE, 1);
			calendar.set(Calendar.HOUR_OF_DAY, dayStart.getHour());
			calendar.set(Calendar.MINUTE, dayStart.getMinute());
			dayStartTimeMilli=calendar.getTimeInMillis();	
		}//dayEnd<=currentTime
		else{
			calendar.add(Calendar.DATE, 1);
			calendar.set(Calendar.HOUR_OF_DAY, dayStart.getHour());
			calendar.set(Calendar.MINUTE, dayStart.getMinute());
			dayStartTimeMilli=calendar.getTimeInMillis();
			
			calendar.set(Calendar.HOUR_OF_DAY, dayEnd.getHour());
			calendar.set(Calendar.MINUTE, dayEnd.getMinute());
			dayEndTimeMilli=calendar.getTimeInMillis();
		}
		
		long repeatTime=24*60*60*1000;
		
		dayAM.cancel(daySender);
		dayAM.setRepeating(AlarmManager.RTC, dayStartTimeMilli, repeatTime, daySender);
		
		nightAM.cancel(daySender);		
		nightAM.setRepeating(AlarmManager.RTC, dayEndTimeMilli, repeatTime, nightSender);
	}
	
	//By GY
	public void resetWallpaperNow() {
    	String currentWeatherStr="";
		String currentDayTimeStr="Night";
		Calendar calendar=Calendar.getInstance();
		MyTime currentTime=new MyTime(calendar.get(Calendar.MINUTE),calendar.get(Calendar.HOUR_OF_DAY));
		if((MyTime.compareTime(dayStartTime, currentTime)==-1||MyTime.compareTime(dayStartTime, currentTime)==0)&&MyTime.compareTime(currentTime, dayEndTime)==-1){
			//是白天
			currentDayTimeStr="Day";
		}
		switch(currentWeather){
		case Calm:
			currentWeatherStr="Calm";
			break;
		case Cloudy:
			currentWeatherStr="Cloudy";
			break;
		case Rainy:
			currentWeatherStr="Rainy";
			break;
		case Snowy:
			currentWeatherStr="Snowy";
			break;
		case Sunny:
			currentWeatherStr="Sunny";
			break;
		default:
			break;
		}
		String preferenceIntKey=currentWeatherStr+currentDayTimeStr+"Int";
		String preferenceStrKey=currentWeatherStr+currentDayTimeStr+"Str";
		SharedPreferences userPreferences = context.getSharedPreferences("WeatherWP",Context.MODE_PRIVATE);
		int pathInt=userPreferences.getInt(preferenceIntKey, 0);
		String pathStr=userPreferences.getString(preferenceStrKey, null);
		Bitmap bm;
		if(pathInt!=0){
			bm=BitmapFactory.decodeResource(context.getResources(),pathInt);
			try {
				context.setWallpaper(bm);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else if(pathStr!=null){
			bm=BitmapFactory.decodeFile(pathStr);
			try {
				context.setWallpaper(bm);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	//TODO:Sgarlic 依据用户的城市获取当前的天气
	public void getCurrentWeather() {
		String provinceName = province.getProvincePinyin();
		String cityName;
		if(province.isMunicipalities())
			cityName = provinceName;
		else
			cityName = city.getCityPinyin();
		System.out.println("province: "+provinceName+";cityName:"+cityName);
		weather.getWeather("china", provinceName, cityName, cityName, new ServiceCallback()
        {
            
            public void onError(String arg0)
            {
            }
            
            public void onComplete(String arg0)
            {
            	String[] tempMessages = arg0.split(",");
            	//先要判断是不是获得成功，成功的标识{"ret":"0"
            	//"weather":{"code":"27"
            	String messageState=(tempMessages[0].split(":"))[1];
            	int messageCode=Integer.parseInt(messageState.substring(1,messageState.length()-1));
            	if(messageCode==0){
	            	String tempWeatherState = (tempMessages[2].split(":"))[2];
	            	int weatherCode = Integer.parseInt(tempWeatherState.substring(1,tempWeatherState.length()-1));
	            	currentWeather = Weather.judgeWeather(weatherCode);
	            	
	            	//设置消息
	                Message msg = new Message();
	                msg.what = 1;
	                msg.obj = arg0;
	                handler.sendMessage(msg); 
            	}
            }
        });
	}

	//By GY
	/*
	 * 再新建一个AlarmManager
	 * 开始运行时间为当前时间
	 * 重复运行间隔是interval
	 * Receiver事件为更新天气信息并依据当前时间和天气更换壁纸
	 */
	private void saveUpdateInterval(int interval){
		Calendar calendar=Calendar.getInstance();
		long updateStartTimeMilli=calendar.getTimeInMillis();
		
		long intervalMilli=interval*60*60*1000;
		//long intervalMilli=5000;
			
		updateAM.cancel(updateSender);
		updateAM.setRepeating(AlarmManager.RTC, updateStartTimeMilli, intervalMilli, updateSender);
	}

	public Province getProvince() {
		return province;
	}

	public void setProvince(Province province) {
		this.province = province;
	}
}
